<script type="text/javascript">
window.dhx_globalImgPath="<?php echo $this->createUrl("/images"); ?>/";

var itemCodeData = <?php echo $item_codes; ?>;
var itemNameData = <?php echo $item_names; ?>;
var itemCostData = <?php echo $item_costs; ?>;

<?php if (isset($line_items)) { echo "var _line_items = {$line_items};"; } ?> 

$(document).ready(function() {

	var lineItemContainer = $("table.invoice-lines");
	var miniumLines = 3;

	var BLANK_LINE = {
			'item_id': '',
			'item_code': '',
			'description': '',
			'unit_cost': '',
			'quantity': '',
			'type': 'item'
	};

	var BLANK_NOTE = {
			'description': '',
			'type': 'note'
	};

	var itemCodeList = [];
	
	$.each(itemCodeData, function(id, code) {
		itemCodeList.push({text: code.htmlentities(), value: id});
	});

	makeComboBox = function(data, container, fieldName) {

		var combo = new dhtmlXCombo(container, fieldName, '133px');
		combo.enableFilteringMode(true);
		combo.addOption(data);

		combo.attachEvent('onSelectionChange', function() {

			var parentRow = $(this.DOMelem).closest('tr');
			
			var combobox = parentRow.find('input[type=hidden]:first').data('combobox');

			selectText = itemNameData[combobox.getSelectedValue()];
			selectCost = itemCostData[combobox.getSelectedValue()];

			description = parentRow.find(".item-desc");
			description.val(selectText);

			cost = parentRow.find(".unit-cost");
			cost.val(selectCost);

			quantity = parentRow.find(".qnty");
			quantity.val(1);
			
			updateLineQuantity(parentRow);
			
		});


		return combo;

	}

	addLine = function(lineItem) {

		var lineType = lineItem['type'];

		if (lineType == 'item') {
			template = getTemplate('#new-item-tpl');
		}
		else if (lineType == 'note') {
			template = getTemplate('#new-note-tpl');
		}
		
		var row = $(template.expand(lineItem));

		if (lineType == 'item') {
			var comboContainer = row.find('div.item-code-container');
			var cbCon = document.createElement("div");

			var comboBox = makeComboBox(itemCodeList, cbCon, 'item_code[]');
	
			comboBox.setComboText(lineItem['item_code']);
		
			comboContainer.append(cbCon);

			$input = $(comboContainer).find('input[type=hidden]:first');
			$input.val(lineItem['item_id']);
			$input.data('combobox', comboBox);
	

			if (lineItem['quantity'] != "") {
				updateLineQuantity(row);
			}
		}

		$('table.invoice-lines tbody').append(row);

		lineItemContainer.tableDnDUpdate();

	}
	
	initLines = function(lines) {

		var numLines = lines['type'].length;

		for (var i = 0; i < numLines; i++) {

			addLine({
				'item_id': lines['item_id'][i],
				'item_code': lines['item_code'][i],
				'description': lines['description'][i],
				'unit_cost': lines['unit_cost'][i],
				'quantity': lines['quantity'][i],
				'note': lines['note'][i],
				'type': lines['type'][i]
				});
		}

	}

	function getTemplate(templateId, args) {
		var tpl = $.support.scriptEval ?
			$(templateId).text() :
			$(templateId).html();

		try {
			return jsontemplate.Template(tpl, $.extend({ undefined_str: '' }, args));
		} catch (exception) {
			alert('Error loading template');
		}
	}

	$('#new-item').click(function() {

		addLine(BLANK_LINE);

		closeDropDownMenu();
		
		return false;
	});

	$('#new-note').click(function() {

		addLine(BLANK_NOTE);

		var tpl = $('#new-note-tpl').html();
		
		closeDropDownMenu();
		
		return false;
	});

	// Draggable table row events
	lineItemContainer.tableDnD({
		dragHandle: "handle",
		onDragClass: "on-drag",
		onDragStart: function() {
			//self.closeOpenDialogs();
			$('td.cell-active').removeClass('cell-active');
			$('body').addClass('cursor-move');
		},
		onDrop: function() {
			$('body').removeClass('cursor-move');
		}
	});


	var container = $('#po-items');

	container.click(function (event) {
		var elem = $(event.target),
						row;

		var divEl = elem.parent().parent();
		
		if (divEl.hasClass('delete')) {

			row = elem.closest('tr');

			row.remove();
			
		}

		return false;
		
	});

	container.change(function (event) {
		var elem = $(event.target),
						row;

		var divEl = elem.parent().parent();

		if (elem.hasClass('qnty')) {

			row = elem.closest('tr');

			updateLineQuantity(row);
			
		}

		return false;
		
	});


	formatAddress = function (field) {

		var vendorId = field.value;

		if (vendorId == 0)
		{
			$('#address-section').hide();
		}
		else {
			dataString = "vendorId="+ field.value;
			
			$.ajax({
				type: "POST",
				url: '<?php echo $this->createUrl("vendor/formatAddress"); ?>',
				data: dataString,
				dataType: 'html',
				success: function (response) {
					$('#address').html(response);
					$('#address-section').show();
				}
			});
		}
	
	};

	$(".dropdown-button").live('click', function (event) {
		var button = $(this);

		// What causes the drop down to close? By default, just a click
		// elsewhere
		var closeHandlers = $(document);
		if (button.is('.no-static')) {
			closeHandlers = closeHandlers.add(button.find('li'));
		}

		function closeMenu(event) {
			if (event.isImmediatePropagationStopped()) {
				return;
			}
			button.removeClass('show-menu');
			closeHandlers.unbind('click', closeMenu);
			event.stopImmediatePropagation();
		}
		
		// Deals with a special case situation where the dhx_combo_box class
		// interferes with other drop downs.
		$('.dhx_combo_box').unbind('click', closeMenu).bind('click', closeMenu);

		$('.show-menu').removeClass('show-menu');
		button.addClass('show-menu');
		closeHandlers.unbind('click', closeMenu).bind('click', closeMenu);
		event.stopImmediatePropagation();
	});

	function closeDropDownMenu()
	{
		$(".dropdown-button").removeClass('show-menu');
	}
	


	// COMBO-BOXES

	

	var i=0;



	function updateLineQuantity(row)
	{
		var cost = row.find(".unit-cost").val();
		var qnty = row.find(".qnty").val();
		var price = row.find(".price");
		var lineTotal = row.find(".total span");
		
		var total = (parseFloat(cost) * parseFloat(qnty));

		lineTotal.html(total);
		price.val(total);

		updatePoTotal();
		
	}

	function updatePoTotal(amount)
	{
		var poTotal = 0;

		$.each(container.find('.price'), function(index) {
			poTotal += parseFloat($(this).val());
		});

		var totalsContainer = $("#amount-row .last-column");
		totalsContainer.html(poTotal);
		
	}


	
	initLines(_line_items);

});

</script>


<div class="title-rule"></div>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'purchase-order-form',
	'enableAjaxValidation'=>false,
)); ?>

<?php echo $form->errorSummary($model); ?>

<div style="position: relative;" class="span-24">
	<div id="client_section" style="display: block;">
		<div class="span-3 required form-layout-left">
			<?php echo $form->labelEx($model,'vendor_id'); ?>
		</div>
		<div class="span-18 form-layout-right">
			<?php 
			$vendorArray = CHtml::listData(Vendor::model()->findAll(),'id','name'); 
			array_unshift($vendorArray, '[Select Vendor]');
			?>

			
			<div class="span-26 append-bottom-1">
				<?php echo $form->DropDownList($model,'vendor_id',$vendorArray, array('style'=>'width:304px;', 'onchange'=>'formatAddress(this);')); ?>
				<?php echo $form->error($model,'vendor_id'); ?>
			</div>

			<div style="display: none;" class="tooble" id="client-help-bubble">
				<b></b>Please select a client for this estimate.
			</div>
		</div>

		<div style="display: none;" class="clearb" id="address-section">
			<div class="span-3 form-layout-left">
				<label class="no-pointer">Address</label>
			</div>
			<div class="span-16 form-layout-right">
				<div id="address" style="height: auto;">
				</div>
				<!-- <a href="#" class="small-link" id="edit-address">Edit Address</a> -->
			</div>
		</div>
	
		<div style="display: none;" class="clearb" id="outstanding-expenses">
			<div class="span-3 form-layout-left"><label class="no-pointer">Expenses</label></div>
			<div class="span-16 form-layout-right">
				<span class="hl">This client has outstanding expenses.</span><br>
				<a id="add-expenses" href="#" class="link-new small-link">Add to invoice</a>
			</div>
		</div>
	</div>
</div>

<div class="span-14">
	
	<div class="span-6 form-layout-left">
		<?php echo $form->labelEx($model,'po_number'); ?>
	</div>
	<div class="span-7 form-layout-right">
		<?php echo $form->textField($model,'po_number',array('style'=>'width: 130px;', 'maxlength'=>20)); ?>
		<?php echo $form->error($model,'po_number'); ?>
	</div>
	
	<div class="span-6 required form-layout-left">
		<label for="js_date">Date of Issue</label>
	</div>
	
	<div class="span-7 form-layout-right">
			
	<input type="text" size="10" value="02/17/11" id="js_date" name="js_date" style="width: 110px;">
			
	<a class="normal" onclick="document.getElementById('js_date').focus(); return false;" href="#">
	<img height="16" border="0" width="16" alt="Click here to launch the calendar widget" src="<?php echo Yii::app()->request->baseUrl; ?>/images/2ndSite/cal.gif"></a>	
	</div>
		
	


	<div class="span-6 form-layout-left">
		<label for="discount_value"><?php echo $form->labelEx($model,'location_id'); ?></label>
	</div>
	<div class="span-7 form-layout-right">
		<?php 
		$locationArray = CHtml::listData(InventoryLocation::model()->findAll(),'id','code'); 
		array_unshift($locationArray, '[Select Location]');
		?>
	
		<div class="span-26 append-bottom-1">
			<?php echo $form->DropDownList($model,'location_id',$locationArray, array('style'=>'width:139px;')); ?>
			<?php echo $form->error($model,'location_id'); ?>
		</div>
	</div>

	
</div>

<div class="clearb"></div>

<table cellspacing="0" style="" class="invoice-lines spreadsheet" id="po-items">
		<thead>
			<tr>
				<th class="first-column" style="width: 1px; padding: 0px;"><img height="1" width="1" alt="" src="<?php echo Yii::app()->request->baseUrl; ?>/images/spacer.gif"></th>
				<td class="action-buttons">
					<!-- 
					<div class="delete"><a href="#"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spreadsheet/delete-color.gif"></a></div>
					 -->
				</td>
				<th style="width: 124px;">Item</th>
				<th style="width: 254px;">Description</th>
				<th class="ta_right" style="width: 68px;">Unit Cost</th>
				<th class="ta_right" style="width: 45px;">Qty</th>
				<th style="width: 62px;">Tax</th>
				<th style="width: 62px;">Tax</th>
				<th class="ta_right last" style="width: 72px;">Line Total</th>
			</tr>
		</thead>
		<tbody>

		</tbody>
	</table>
	
<div class="totals">
	<div class="rule top"></div>
	
    <div class="float_left">
    	
    	<div class="spreadsheet actions">
    		<ul>
    			<li class="dropdown-button no-static" style="display: block;">
    				<span style="float: left;"><a onclick="return false;" href="#"><div></div>Add Line</a></span>
    				<ul>
    					<li><a id="new-item" href="#">Add Item</a></li>
    					<li><a id="new-note" href="#">Add Note</a></li>
    				</ul>
    			</li>
    		</ul>
    	</div>
    	
    </div>
		
	<div class="box">
		<table cellspacing="0" class="table-totals">
			<thead style="display: none;">
				<tr id="subtotal-row">
					<td style="width: 20px;">&nbsp;<input type="hidden" name="subtotal" readonly="" style="width: 100%;" value="9.99"></td>
					<th style="width: 150px;">Subtotal</th>
					<td class="last-column">$0.00</td>
				</tr>

				<tr style="display: none;" id="discount-total-row">
					<td style="width: 20px;">&nbsp;<input type="hidden" name="discount_total" readonly="" style="width: 100%;" value="0.00"></td>
					<th style="width: 150px;">Discount</th>
					<td class="last-column">0.00</td>
				</tr>
				
				<!-- taxes go here -->
				<tr class="divider">
					<td><div></div></td>
					<td><div></div></td>
					<td><div></div></td>
				</tr>
			</thead>
			<tbody>			
				<tr id="amount-row" class="invoice-total-box">
					<td style="width: 20px;">&nbsp;<input type="hidden" name="amount" readonly="" style="width: 100%;" value="9.99"></td>
					<th style="width: 150px;">PO Total <span class="currency">(USD)</span></th>
					<td class="last-column">0.00</td>
				</tr>
							</tbody>
		</table>
	</div>

	<div class="clearb"></div>

	<div class="functions">
				
				
		<span style="display: none;" id="credit">
			<span class="hl">
				<input type="checkbox" id="apply_credit" name="apply_credit" value="1" class="checkbox" style="width: 15px;">
				<label for="apply_credit" style="cursor: pointer;">Apply credit of <span id="credit_amount"></span>&nbsp;as payment</label>
			</span>
		</span>

	</div>
	<div class="clearb"></div>
</div>
	
<div class="append-bottom-1 form-layout">
	<div class="span-20 append-4 append-bottom-1 iefix-2">
		<label for="terms">Terms</label>
					(<a class="small-link" rel="estimates" id="launch-termspop" href="#">Set Default Terms</a>)
					
		<textarea id="terms" name="terms" style="width: 100%; height: 90px;"></textarea>
	</div>

	<div class="span-14 append-bottom-1">
		<label for="notes">Notes Visible to Client</label>
		<textarea name="notes" id="notes" style="width: 272px; height: 90px;"></textarea>
	</div>

	<div style="clear: both;"></div>
</div>

<script type="text/html" id="new-item-tpl">
	<tr style="">
		<td class="handle">
			<div><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spreadsheet/drag-color.gif" /></div>
		</td>
		<td class="action-buttons">
			<div class="insert"><a href="#"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spreadsheet/add.gif" /></a></div>
			<div class="delete"><a href="#"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spreadsheet/delete-color.gif" /></a></div>
		</td>
		<td class="first-column has-combobox editable">
			<div class="item-code-container"> 

			</div>
		</td>
		<td class="editable">
			<input class="item-desc" type="text" name="item-desc[]" style="overflow: hidden; display: block; height: 22px;" value="{description|html-attr-value}" />
		</td>
		<td class="editable">
			<input class="unit-cost" name="unit_cost[]" type="text" class="ta_right iefix-3 ie7fix-1" value="{unit_cost|html-attr-value}"/>
		</td>
		<td class="editable">
			<input class="qnty" name="qnty[]" type="text" class="ta_right iefix-3 ie7fix-1" value="{quantity|html-attr-value}"/>
		</td>
		<td class="editable has-combobox">
			<div class="tax1-container"></div>
		</td>
		<td class="editable has-combobox">
			<div class="tax2-container"></div>
		</td>
		<td class="total">
			<span class="ta_right">0.00</span><!-- price -->
			<input class="price" type="hidden" name="price[]" value="0.00"/>
			<input type="hidden" name="note[]" value=""/>
			<input type="hidden" name="line_type[]" value="item"/>
			<input type="hidden" name="lineid[]" value="" />
		</td>
	</tr>
</script>

<script type="text/html" id="new-note-tpl">
	<tr style="">
		<td class="handle">
			<div><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spreadsheet/drag-color.gif"></div>
		</td>
		<td class="action-buttons">
			<div class="insert"><a href="#"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spreadsheet/add.gif" /></a></div>
			<div class="delete"><a href="#"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spreadsheet/delete-color.gif" /></a></div>
		</td>
		<td class="editable" colspan="6">
			<input class="note" type="text" name="note[]" style="overflow: hidden; display: block; height: 22px;" value="{note|html-attr-value}" />
		</td>
		<td class="total">
			<input type="hidden" name="price[]" value=""/>
			<input type="hidden" name="qnty[]" value=""/>
			<input type="hidden" name="unit_cost[]" value=""/>
			<input type="hidden" name="item_code[]" value=""/>
			<input type="hidden" name="line_type[]" value="note"/>
			<input type="hidden" name="lineid[]" value="">
		</td>
	</tr>
</script>

<div class="edit-end"></div>

<div style="text-align:center;">
	<?php echo CHtml::imageButton("/cloverdale/images/buttons/save.gif"); ?>
</div>
		
<?php $this->endWidget(); ?>

</div><!-- form -->